<template>
    <div class="page-edit" :class="[{'p30': hideStep}]" v-loading="loading">
        <el-form ref="editRef" :model="formData" :rules="formRule" :label-width="110">
            <el-form-item label="课程章节名称" prop="title" class="srt-el-input-item">
                <el-input show-word-limit maxlength="50" type="text" v-model="formData.title"
                    class="srt-el-input input-width" placeholder="请输入课程章节名称，最多50个字">
                </el-input>
            </el-form-item>
            <el-form-item label="学段学科年级" prop="stageSubjectList">
                <div class="stage">
                    <stage-subject ref="ssRef" isShowGrade @update:selectedData="updateStage"
                        :selectedData="formData.stageSubjectList" placeholder="请选择学段学科年级">
                    </stage-subject>
                </div>
            </el-form-item>
            <!-- <el-form-item label="年级" prop="gradeIds">
                <el-select v-model="formData.gradeIds" placeholder="请选择年级" size="large"
                    :class="['select-width', 'srt-select', { 'srt-clear-select': formData.gradeIds }]" 
                    popper-class="srt-select-popper" multiple>
                    <el-option v-for="item in gradeList" :label="item.name" :value="item.code" :key="item.code" />
                </el-select>
            </el-form-item> -->
            <el-form-item label="教师团队" prop="lecturerList" class="form-teacher">
                <div>
                    
                    <el-button class="srt-el-button srt-el-button-h32 add-btn" type="default" :disabled="formData?.lecturerList?.length === 9"
                        @click="addTeacher">
                        添加教师成员
                    </el-button>
                    <span class="add-tip">如添加多位教师可拖拽进行排序</span>
                    <draggable :animation="500"
                        v-if="formData.lecturerList?.length"
                        :class="['teacher-list']"
                        :list="formData.lecturerList"
                        group="teacher-list"
                        ghost-class="ghost"
                        drag-class="chosen"
                        :options="{ draggable: '.teacher-item' }">
                        <li v-for="(item, index) in formData.lecturerList" :key="index" class="teacher-item">
                            <img class="head-img" :src="item.picture || ImgHead" />
                            <div class="teacher-content">
                                <p class="name">{{item.name}}</p>
                                <p class="address">{{item.workPlace}}</p>
                                <p class="desc">{{item.description || '暂无简介'}}</p>
                            </div>
                            <div class="teacher-icon">
                                <i class="iconfont icon-bianji" @click="addTeacher(item)"></i>
                                <i class="iconfont icon-shanchu" @click="deleteTeacher(index)"></i>
                            </div>
                        </li>
                    </draggable>
                </div>
            </el-form-item>
        </el-form>
    </div>
    <div class="edit-submit">
        <el-button class="srt-el-button srt-el-button--primary srt-el-button-h36 btn" :class="[{'btn-save': hideStep}]" @click="save" type="primary">
            {{ hideStep ? '保存' : '保存并下一步' }}
        </el-button>
    </div>
    <LectureDialog v-model="showDialog" :form="lectureInfo" @update-lecture="updateLecture" />
</template>
<script setup>
import { VueDraggableNext as draggable } from "vue-draggable-next";
import StageSubject from '@/components/stage-subject/stage-subject-grade.vue';
import LectureDialog from './dialog/lecture-dialog.vue';
import { ref, computed, onMounted, watch } from 'vue';
import { useStore } from 'vuex';
import { queryToJson } from '@/lib/tools.js';
import { useRoute } from 'vue-router';
import Confirm from '@/components/confirm/confirm.js';
import ImgHead from '@/assets/img/mooc/img-head.png';

const route = useRoute();

const store = useStore();

const emit = defineEmits(['change-step', 'back']);

const props = defineProps({
    detail: {
        type: Object,
        default: () => {
            return {};
        }
    }
})

const hideStep = computed(() => {
    return route.query.type == 1;
})

const formRule = ref({
    title: [
        {
            required: true,
            validator: (rule, value, callback) => {
                let temp = value && value.trim() || '';
                if (temp.length > 50 || temp.length < 2) {
                    callback('请输入2-50个字的课程章节名称');
                }else {
                    callback();
                }
            },
            trigger: 'blur'
        }
    ],
    stageSubjectList: [
        { required: true, message: '请选择学段学科年级', trigger: 'blur' }
    ],
    lecturerList: [
        {
            required: true,
            validator: (rule, value, callback) => {
                if (value && value.length) {
                    callback();
                } else {
                    callback(new Error('请至少添加一名教师'));
                }
            },
            trigger: 'none'
        }
    ]
});

const formData = ref({
    lecturerList: []
});


const loading = ref(true);

const showDialog = ref(false);

const editRef = ref(null);
// 讲师信息
const lectureInfo = ref({});


watch(() => props.detail, (val) => {
    if(val) {
        loading.value = false;
        formData.value = val;
        formData.value.stageSubjectList = fmtStageResponse();
        // formData.value.gradeIds = fmtGradeResponse();
    }
})


// 年级列表
const gradeList = computed(() => {
    const ids = formData.value?.stageSubjectList?.length && formData.value.stageSubjectList.map(item => Number(item.stageId)) || [];
    const list = store.state.common.stageRefSubject
        .filter(item => ids.includes(item.stage))
        .filter(item => item.grades)
        .map(item => item.grades && item.grades.map(g => ({ ...g, pid: item.stage })) || [])
        .flat();
    return list || [];
})

// 更新学段学科
function updateStage (data) {
    formData.value.stageSubjectList = data;
    // formData.value.gradeList = [];
    // formData.value.gradeIds = [];
}




// 添加老师
function addTeacher (data = {}) {
    lectureInfo.value = data;
    showDialog.value = true;
}

// 删除老师
function deleteTeacher(index) {
    Confirm(
        { 
            title: '温馨提示', 
            text: '确认要删除该教师吗？'
        }
    )
    .then(ret => {
        formData.value.lecturerList.splice(index, 1);
    })
    .catch(_err => {
        console.log(_err);
    }) 
}

function updateLecture(data) {
    let index = formData.value.lecturerList.findIndex(item => item.id === data.id);
    if(index === -1) {
       formData.value.lecturerList.push(data);
    }else {
       formData.value.lecturerList[index] = data;
    }
}


/**
 * 格式化给后台传的年级参数
 */
function fmtGradeParams () {
    let checkIds = formData.value?.stageSubjectList || [];
    let checkList = [];
    checkIds.forEach(item => {
        if(item.gradeList?.length) {
            checkList = checkList.concat(item.gradeList);
        }
    });
    return checkList;
    //  let checkIds = formData.value?.gradeIds.length ? formData.value?.gradeIds : [];
    //  let checkList = checkIds.map(item => {
    //     let temp = gradeList.value?.length && gradeList.value.find(grade => grade.code === item);
    //     return {gradeId: temp.code, gradeName: temp.name};
    //  }) || [];
    //  return checkList
}

/**
 * 格式化后台回显的数据
 */
function fmtGradeResponse () {
     return formData.value?.gradeList?.length && formData.value?.gradeList.map(item => item.gradeId) || [];
}

/**
 * 格式化后台回显的数据
 */
 function fmtStageResponse () {
    let gradeMap = {};
    const list = store.state.common.stageRefSubject;
    list.length && list.forEach(item => {
        if(item.grades?.length) {
            item.grades.forEach(gradeItem => {
                gradeMap[gradeItem.code] = Object.assign(gradeItem, {stage: item.stage});
            })
        }
    });
    let gradeStageMap = {};
    formData.value.gradeList?.length && formData.value.gradeList.forEach(item => {
        let oldGrade = gradeMap[item.gradeId];
        if(oldGrade) {
            if(gradeStageMap[oldGrade.stage]?.length) {
                gradeStageMap[oldGrade.stage].push(item);
            }else {
                gradeStageMap[oldGrade.stage] = [item];
            }
        }
    })

    let subjectStageList = formData.value.stageSubjectList || [];
    return subjectStageList.map(item => {
        item.gradeList = gradeStageMap[item.stageId] || [];
        return item;
    })
}


function save () {
    if (formData.value.publishState === 1) {
        G_dispatchEvent('toast', { message: '课程已发布，请取消发布后再操作', type: 'error' })
        return;
    }
    
    editRef.value.validate((valid) => {
        if (!valid) {
            G_dispatchEvent('toast', { message: '请检查必填项', type: 'error' })
            return;
        }
        let portalName = formData.value.id ? 'courseUpdate' : 'courseCreate';
        loading.value = true;
        let params = {
            ...formData.value,
            bizSourceId: 0,
            templateId: 0,
            bizSource: 'mooc',
            type: 'mooc',
            state: 1,
            gradeList: fmtGradeParams()
        };
        params.stageSubjectList = params.stageSubjectList || [];
        if (params.stageSubjectList && params.stageSubjectList.length <= 0) {
            delete params.stageSubjectList
        }
        params.gradeList = params.gradeList || [];
        if (params.gradeList && params.gradeList.length <= 0) {
            delete params.gradeList;
        }
        G_transmit(portalName, {
            data: params
        })
            .then((res) => {
                let tip = formData.value.id ? '编辑成功' : '创建成功';
                G_dispatchEvent('toast', { message: tip, type: 'success' });
                if(hideStep.value) {
                    back();
                    return;
                }
                emit('change-step', 2);
                let courseId = res.data || queryToJson().courseId;
                let tabStr = queryToJson().tabStr;
                if(courseId) {
                    window.history.pushState('', '', `?courseId=${courseId}&step=2&tabStr=${tabStr || ''}`);
                }else {
                    window.history.pushState('', '', `?step=2&tabStr=${tabStr || ''}`)
                }
            })
            .catch((err) => {
                console.log(err)
            }).finally(() => {
                loading.value = false;
            });
    })
}

function getDetail () {
    let courseId = queryToJson().courseId || route.params.courseId;
    if(!courseId) {
        return;
    }
    loading.value = true;
    G_transmit('courseDetail', {
        queries: {
           id: courseId
        }
    })
    .then((res) => {
        formData.value = res.data || {};
        formData.value.gradeIds = fmtGradeResponse();
    })
    .catch((err) => {
        console.log(err)
    }).finally(() => {
        loading.value = false;
    });
}

function back() {
    emit('back');
}


onMounted(() => {
    let courseId = queryToJson().courseId || route.params.courseId;
    if(!courseId) {
        loading.value = false;
    }
})



</script>

<style lang="scss" scoped>
.page-edit {
    background: #ffffff;
    padding: 0px 30px 10px;

    :deep(.el-form-item) {
        margin-bottom: 30px;
    }

    :deep(.el-form-item__label) {
        line-height: 40px;
        height: 40px;
        color: var(--srt-color-gray);
        margin-right: 8px;
    }
    .input-width {
        width: 915px;
    }

    .select-width {
        width: 460px;
    }
    .stage {
        width: 460px;

        :deep(.sss) {
            min-height: 38px;
        }
        :deep(.ss) {
            margin-top: 2px;
        }
        :deep(.sss-no-padding > .ss) {
            line-height: 38px;
            margin-top: 0px;
        }
       
    }
    .teacher-list {
        display: flex;
        flex-wrap: wrap;
        margin-top: 20px;
        li {
            width: 330px;
            height: 160px;
            background: #F7F9FA;
            border-radius: 5px;
            display: flex;
            padding: 14px;
            margin-bottom: 20px;
            margin-right: 16px;
            position: relative;
            border: 1px solid #F7F9FA;
            &:nth-child(3n) {
                margin-right: 0px;
            }
            &:nth-child(3n+1):nth-last-child(-n+3),
            &:nth-child(3n+1):nth-last-child(-n+3)~.li{
                margin-bottom: 0;
            }
            &:hover {
                border: 1px solid #E4E9EE;
            }
        }
        .head-img {
            width: 100px;
            height: 132px;
            border-radius: 4px;
            margin-right: 14px;
        }
        .teacher-content {
            padding-top: 13px;
        }
        .name {
            font-size: 16px;
            color: var(--srt-main-text-color);
            max-width: 108px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            line-height: 1;
        }
        .address {
            font-size: 14px;
            margin-top: 8px;
            max-width: 186px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            line-height: 1;
        }
        .desc {
            width: 100%;
            word-break: break-all;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 3; /* 这里是超出几行省略 */
            overflow: hidden;
            margin-top: 14px;
            line-height: 18px;
            color: var(--color-gray);
        }
    }
}
.form-teacher {
    :deep(.el-form-item__label) {
        line-height: 30px !important;
        height: 30px !important;
    } 
    .add-btn {
        width: 120px;
    }
}

.edit-submit {
    padding: 30px 0px 0px;
    text-align: center;
    .btn {
        padding: 0px 18px;
    }
    .btn-save {
        padding: 0px 45px;
    }
} 
.teacher-icon {
    position: absolute;
    right: 16px;
    top: 8px;
    .iconfont {
        font-size: 18px;
        margin-left: 12px;
        cursor: pointer;
        color: var(--srt-color-gray);
        &:hover {
            color: var(--srt-main-active-text-color);
        } 
    }
}

.add-tip {
    font-size: 12px;
    color: var(--srt-color-light-gray);
    margin-left: 12px;
    display: inline-block;
}

.teacher-item {
    transition: all 0.2s;
    cursor: move;
}

.p30 {
    padding-top: 30px;
}

</style>